<script lang="ts" setup>
import { useWindowScroll, watchThrottled, useIntersectionObserver } from '@vueuse/core'
import { onMounted, ref } from 'vue';
import { useFetch } from '@/mobile/hooks/fetch';
import { useAsyncData } from '@/mobile/hooks/async-data';

export interface EngagementData {
  informationLikeCount: number;
  informationCollections: number;
  informationViews: number;
  isLike: boolean;
  isCollect: boolean;
}

const { $fetch } = useFetch();
const { y } = useWindowScroll(); // 获取滚动位置
const baseScrollY = ref(0); // 记录基准点滚动位置
const isFixed = ref(false); // 控制是否设置 fixed 样式
const sidePanel = ref<HTMLElement>()
const loading = ref(false);
const isVisible = ref(true); // 是否在视口内的状态

const props = defineProps<{
  id: string;
}>();


const { data, refresh } = useAsyncData<EngagementData>(
  'mobile:detail:sidePanel:engagement',
  () => $fetch<EngagementData>('/information/like/num', { data: { informationId: props.id } }),
  {
    cache: false,
    watch: [() =>  props.id],
  },
)

const saveEngagement = async (type: number) => {
  if (loading.value) {
    return;
  }

  loading.value = true;

  const { isSuccess } = await $fetch('/information/like', {
    method: 'post',
    params: {
      informationId: props.id,
      type,
    },
    autoGotoLogin: true,
  });

  loading.value = false;

  if (isSuccess) {
    await refresh();
  }
};

const SCROLL_THRESHOLD = 200; // 触发判断的滚动距离阈值

// 滚动逻辑控制
const handleScroll = (currentY: number) => {
  // 计算当前滚动距离和基准点的差值
  const distanceScrolled = currentY - baseScrollY.value;

  if (!isVisible.value) {
    // 向下滚动超过 SCROLL_THRESHOLD
    if (distanceScrolled > SCROLL_THRESHOLD) {
      isFixed.value = false;
      baseScrollY.value = currentY; // 重置基准点
    }
    // 向上滚动超过 SCROLL_THRESHOLD
    else if (distanceScrolled < -SCROLL_THRESHOLD || currentY === 0) {
      isFixed.value = true;
      baseScrollY.value = currentY; // 重置基准点
    }
  } else {
    isFixed.value = false;
  }
}

onMounted(() => {
  useIntersectionObserver(
    sidePanel,
    ([{ isIntersecting }]) => {
      isVisible.value = isIntersecting
      // 立即执行一次初始滚动检查
      handleScroll(y.value);
    },
  )

  // 监听滚动变化
  watchThrottled(y, (value) => {
    handleScroll(value);
  }, {
    throttle: 100,
  });
});
</script>

<template>
  <div ref="sidePanel" class="mt-32 h-56">
    <div class="w-full bg-#fff shadow-[0_1px_6px_0_rgba(0,0,0,0.06)]" :class="[isFixed ? 'fixed pb-[env(safe-area-inset-bottom)] bottom-0' : 'relative']" v-if="data">
      <div class="flex items-center justify-between px-20 py-10">
        <div class="flex items-center gap-6 rounded-17 px-16 py-8" :class="[data.isLike ? 'bg-[rgba(61,124,250,0.1)] text-#3d7cfa' : 'bg-#fafafa text-#575757']" @click="saveEngagement(1)">
          <div class="size-20" :class="[data.isLike ? 'i-icons:good-filled' : 'i-icons:good']"></div>
          <div class="text-14 font-400 leading-20">{{ $t('mobile.home.detail.like', { like: data.informationLikeCount }) }}</div>
        </div>
        <div :class="[data.isCollect ? ' text-#3d7cfa' : ' text-#575757']">
          <div class="mx-auto size-20" :class="[data.isCollect ? 'i-icons:favorite-filled' : 'i-icons:favorite']"></div>
          <div class="mt-4 min-w-32 text-center text-12 font-400 leading-12" @click="saveEngagement(2)">{{ data.isCollect ? data.informationCollections : $t('mobile.home.detail.collect') }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
</style>
